// 主题管理Hook
// 提供主题切换和系统主题监听功能

import { useEffect } from 'react';
import { useLayoutStore, Theme, applyTheme } from '../stores/layoutStore';

export const useTheme = () => {
  const { theme, setTheme, toggleTheme, setFollowSystem } = useLayoutStore();

  // 监听系统主题变化
  useEffect(() => {
    if (!theme.followSystem || theme.current !== Theme.Auto) {
      return;
    }

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    
    const handleThemeChange = () => {
      applyTheme(Theme.Auto);
    };

    // 初始应用
    handleThemeChange();
    
    // 监听变化
    mediaQuery.addEventListener('change', handleThemeChange);
    
    return () => {
      mediaQuery.removeEventListener('change', handleThemeChange);
    };
  }, [theme.followSystem, theme.current]);

  // 应用主题变化
  useEffect(() => {
    applyTheme(theme.current);
  }, [theme.current]);

  return {
    currentTheme: theme.current,
    followSystem: theme.followSystem,
    setTheme,
    toggleTheme,
    setFollowSystem,
  };
};
